from paddleocr import PaddleOCR
import os
import json
from logger_config import setup_logger

# 创建日志记录器
logger = setup_logger('ocr_service')

# 全局变量，用于缓存已加载的OCR模型
OCR_MODEL = None

def load_ocr_model():
    """
    加载OCR模型
    
    Returns:
        PaddleOCR模型实例
    """
    global OCR_MODEL
    if OCR_MODEL is None:
        logger.info("加载OCR模型...")
        try:
            OCR_MODEL = PaddleOCR(
                text_detection_model_name="PP-OCRv5_server_det",
                text_recognition_model_name="PP-OCRv5_server_rec",
                use_doc_orientation_classify=False,
                use_doc_unwarping=False,
                use_textline_orientation=False,
            )
            logger.info("OCR模型加载成功")
        except Exception as e:
            error_msg = f"加载OCR模型失败: {str(e)}"
            logger.error(error_msg)
            raise
    return OCR_MODEL

def recognize_license_plate(image_path, output_dir):
    """
    识别车牌文本
    
    Args:
        image_path (str): 车牌图像路径
        output_dir (str): 输出目录
    
    Returns:
        tuple: (识别结果图像路径, 识别文本, 置信度)
    """
    logger.info(f"开始识别车牌文本: {image_path}")
    
    try:
        # 加载OCR模型
        ocr = load_ocr_model()
        
        # 执行OCR识别
        result = ocr.predict(image_path)
        
        # 提取文件名（不含扩展名）用于保存结果
        base_filename = os.path.basename(image_path)
        filename_without_ext = os.path.splitext(base_filename)[0]
        
        # 识别结果和置信度
        plate_text = ""
        confidence = 0.0
        
        # 保存OCR结果图像和JSON
        for res in result:
            # 保存结果图像
            ocr_res_img_path = os.path.join(output_dir, f"{filename_without_ext}_ocr_res_img.jpg")
            res.save_to_img(output_dir)
            
            # 保存JSON结果
            json_path = os.path.join(output_dir, f"{filename_without_ext}_res.json")
            res.save_to_json(output_dir)
            
            # 读取JSON文件获取识别文本和置信度
            with open(json_path, 'r', encoding='utf-8') as f:
                json_data = json.load(f)
                
            # 提取识别文本和置信度
            if json_data.get('rec_texts') and len(json_data['rec_texts']) > 0:
                plate_text = json_data['rec_texts'][0]
                confidence = json_data['rec_scores'][0] if json_data.get('rec_scores') and len(json_data['rec_scores']) > 0 else 0.0
        
        logger.info(f"车牌文本识别完成: {plate_text}, 置信度: {confidence}")
        
        return ocr_res_img_path, plate_text, confidence
        
    except Exception as e:
        error_msg = f"车牌文本识别失败: {str(e)}"
        logger.error(error_msg)
        raise 